package faa.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;


public class ConvertingUtils {

	public static Object byteArrayToSerializable(byte[] data) {
		ObjectInputStream objectIStream = null;
		try {
			objectIStream = new ObjectInputStream(
					new ByteArrayInputStream(data));
			return objectIStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Wrong serialized data");
		} finally {
			if (objectIStream != null)
				try {
					objectIStream.close();
				} catch (IOException e) {}
		}
	}

	public static Object hexToSerializable(String string) {
		return byteArrayToSerializable(hexToByteArray(string));
	}

	public static String byteArrayToHex(byte[] buff) {
		return new BigInteger(buff).toString(16);
	}

	public static byte[] hexToByteArray(String string) {
		return new BigInteger(string, 16).toByteArray();
	}

	public static byte[] serializableToByteArray(Serializable object) throws IOException {
		ByteArrayOutputStream buff = new ByteArrayOutputStream();
		ObjectOutputStream objectOStream = new ObjectOutputStream(buff);
		objectOStream.writeObject(object);
		return buff.toByteArray();
	}

	public static String serializableToHex(Serializable object) throws IOException {
		return byteArrayToHex(serializableToByteArray(object));
	}

}
